<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getProjects, getCases, getSuites, getLogStatistics } from '@/api/index.js'
import useUserInfoStore from "@/store/user.js"
import { 
  TrendCharts, 
  DataAnalysis, 
  Document, 
  Files,
  CollectionTag,
  Warning
} from '@element-plus/icons-vue'

const userStore = useUserInfoStore()
const loading = ref(false)

const dashboardData = ref({
  projects: {
    total: 0,
    active: 0,
    completed: 0
  },
  cases: {
    total: 0,
    high_priority: 0,
    medium_priority: 0,
    low_priority: 0
  },
  suites: {
    total: 0,
    active: 0
  },
  logs: {
    total: 0,
    success: 0,
    failed: 0,
    error: 0
  }
})

const recentActivities = ref([
  { id: 1, type: 'project', action: '创建了项目', name: '用户管理系统测试', time: '2小时前' },
  { id: 2, type: 'case', action: '添加了测试用例', name: '用户登录接口测试', time: '4小时前' },
  { id: 3, type: 'suite', action: '执行了测试套件', name: '用户模块测试套件', time: '6小时前' },
  { id: 4, type: 'log', action: '查看了日志', name: '系统运行日志', time: '8小时前' }
])

const fetchDashboardData = async () => {
  loading.value = true
  try {
    // 获取项目统计
    const projectRes = await getProjects({ page: 1, size: 1000 })
    if (projectRes.status === 200) {
      const projects = projectRes.data.results || []
      dashboardData.value.projects.total = projects.length
      dashboardData.value.projects.active = projects.filter(p => p.status === 'ACTIVE').length
      dashboardData.value.projects.completed = projects.filter(p => p.status === 'COMPLETED').length
    }

    // 获取用例统计
    const caseRes = await getCases({ page: 1, size: 1000 })
    if (caseRes.status === 200) {
      const cases = caseRes.data.results || []
      dashboardData.value.cases.total = cases.length
      dashboardData.value.cases.high_priority = cases.filter(c => c.priority === 'HIGH').length
      dashboardData.value.cases.medium_priority = cases.filter(c => c.priority === 'MEDIUM').length
      dashboardData.value.cases.low_priority = cases.filter(c => c.priority === 'LOW').length
    }

    // 获取套件统计
    const suiteRes = await getSuites({ page: 1, size: 1000 })
    if (suiteRes.status === 200) {
      const suites = suiteRes.data.results || []
      dashboardData.value.suites.total = suites.length
      dashboardData.value.suites.active = suites.filter(s => s.status === 'ACTIVE').length
    }

    // 获取日志统计
    const logRes = await getLogStatistics()
    if (logRes.status === 200) {
      dashboardData.value.logs = logRes.data
    }
  } catch (error) {
    ElMessage.error('获取仪表盘数据失败')
  } finally {
    loading.value = false
  }
}

const getUserTypeDisplay = (userType) => {
  const typeMap = {
    'ADMIN': '管理员',
    'TESTER': '测试工程师', 
    'DEVELOPER': '开发工程师',
    'MANAGER': '测试管理员',
    'VIEWER': '报告查看者'
  }
  return typeMap[userType] || userType
}

const getActivityColor = (type) => {
  const colorMap = {
    'project': '#1976d2',
    'case': '#388e3c', 
    'suite': '#f57c00',
    'log': '#c2185b'
  }
  return colorMap[type] || '#909399'
}

const getActivityIcon = (type) => {
  const iconMap = {
    'project': Files,
    'case': Document,
    'suite': CollectionTag,
    'log': Warning
  }
  return iconMap[type] || Document
}

onMounted(() => {
  fetchDashboardData()
})
</script>

<template>
  <div class="dashboard" v-loading="loading">
    <!-- 欢迎区域 -->
    <el-card class="welcome-card">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来，{{ userStore.userInfo.username }}！</h2>
          <p>您的身份：{{ getUserTypeDisplay(userStore.userInfo.user_type) }}</p>
          <p>今天是 {{ new Date().toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            weekday: 'long'
          }) }}</p>
        </div>
        <div class="welcome-icon">
          <el-icon :size="80" color="#409eff">
            <DataAnalysis />
          </el-icon>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="statistics-row">
      <!-- 项目统计 -->
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-content">
            <div class="statistic-icon project">
              <el-icon :size="32">
                <Files />
              </el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-number">{{ dashboardData.projects.total }}</div>
              <div class="statistic-label">项目总数</div>
              <div class="statistic-detail">
                进行中: {{ dashboardData.projects.active }} | 
                已完成: {{ dashboardData.projects.completed }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 用例统计 -->
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-content">
            <div class="statistic-icon case">
              <el-icon :size="32">
                <Document />
              </el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-number">{{ dashboardData.cases.total }}</div>
              <div class="statistic-label">测试用例</div>
              <div class="statistic-detail">
                高: {{ dashboardData.cases.high_priority }} | 
                中: {{ dashboardData.cases.medium_priority }} | 
                低: {{ dashboardData.cases.low_priority }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 套件统计 -->
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-content">
            <div class="statistic-icon suite">
              <el-icon :size="32">
                <CollectionTag />
              </el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-number">{{ dashboardData.suites.total }}</div>
              <div class="statistic-label">测试套件</div>
              <div class="statistic-detail">
                激活: {{ dashboardData.suites.active }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 日志统计 -->
      <el-col :span="6">
        <el-card class="statistic-card">
          <div class="statistic-content">
            <div class="statistic-icon log">
              <el-icon :size="32">
                <Warning />
              </el-icon>
            </div>
            <div class="statistic-info">
              <div class="statistic-number">{{ dashboardData.logs.total }}</div>
              <div class="statistic-label">日志记录</div>
              <div class="statistic-detail">
                成功: {{ dashboardData.logs.success }} | 
                失败: {{ dashboardData.logs.failed }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 内容区域 -->
    <el-row :gutter="20" class="content-row">
      <!-- 最近活动 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-button size="small" @click="fetchDashboardData">刷新</el-button>
            </div>
          </template>
          <div class="activity-list">
            <div v-for="activity in recentActivities" :key="activity.id" class="activity-item">
              <div class="activity-icon">
                <el-icon :size="16" :color="getActivityColor(activity.type)">
                  <component :is="getActivityIcon(activity.type)" />
                </el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-text">
                  {{ activity.action }} <strong>{{ activity.name }}</strong>
                </div>
                <div class="activity-time">{{ activity.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 快速操作 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button type="primary" size="large" @click="$router.push('/project-create')">
              <el-icon><Files /></el-icon>
              创建项目
            </el-button>
            <el-button type="success" size="large" @click="$router.push('/case-create')">
              <el-icon><Document /></el-icon>
              新建用例
            </el-button>
            <el-button type="warning" size="large" @click="$router.push('/suite-create')">
              <el-icon><CollectionTag /></el-icon>
              创建套件
            </el-button>
            <el-button type="info" size="large" @click="$router.push('/logs')">
              <el-icon><TrendCharts /></el-icon>
              查看日志
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="less">
.dashboard {
  padding: 20px;

  .welcome-card {
    margin-bottom: 20px;
    
    .welcome-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .welcome-text {
        h2 {
          margin: 0 0 10px 0;
          color: #303133;
        }
        
        p {
          margin: 5px 0;
          color: #606266;
        }
      }
    }
  }

  .statistics-row {
    margin-bottom: 20px;

    .statistic-card {
      .statistic-content {
        display: flex;
        align-items: center;
        
        .statistic-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          
          &.project {
            background-color: #e3f2fd;
            color: #1976d2;
          }
          
          &.case {
            background-color: #e8f5e8;
            color: #388e3c;
          }
          
          &.suite {
            background-color: #fff3e0;
            color: #f57c00;
          }
          
          &.log {
            background-color: #fce4ec;
            color: #c2185b;
          }
        }
        
        .statistic-info {
          .statistic-number {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
          }
          
          .statistic-label {
            font-size: 14px;
            color: #909399;
            margin: 5px 0;
          }
          
          .statistic-detail {
            font-size: 12px;
            color: #c0c4cc;
          }
        }
      }
    }
  }

  .content-row {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .activity-list {
      .activity-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .activity-icon {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background-color: #f5f7fa;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
        }
        
        .activity-content {
          flex: 1;
          
          .activity-text {
            font-size: 14px;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .activity-time {
            font-size: 12px;
            color: #c0c4cc;
          }
        }
      }
    }

    .quick-actions {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
      
      .el-button {
        height: 60px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8px;
      }
    }
  }
}
</style>